package com.wgj.android.accesslibility.job;

import android.accessibilityservice.AccessibilityService;
import android.app.Notification;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Handler;
import android.support.annotation.RequiresApi;
import android.util.Log;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;

import com.jiaai.xui.cache.XCache;
import com.jiaai.xui.utils.XDateUtils;
import com.jiaai.xui.view.widget.XToast;
import com.wgj.android.accesslibility.AccessibilityHelper;
import com.wgj.android.accesslibility.IStatusBarNotification;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;

/**
 * Created by Administrator on 2017/11/11.
 */

public class WXMultipleShareJob implements AccessbilityJob {
    private AccessibilityService service;
    private static  final   String  TAG="WXShare";
    private  static  final  String MANY_SHARE_CACHE_KEY="_many_share_cache_key"; //高级分享绶存标识
    private  static  final  String SHARE_CACHE_KEY="share_cache_key"; //普通分享绶存标识
    private  static  final  String checkBoxId="com.tencent.mm:id/pt"; //联系人列表单选按钮
    private  static  final  String CONTACT_ITEM_ID="com.tencent.mm:id/c55"; //联系人
    private  static AccessibilityNodeInfo listView=null; //联系人列表
    private  static  int selectIndex=0; //当前已选择的人数
    private static   boolean isNotMore=false; //是否已到底部的标识
    private static HashSet<String> shareSelects=new HashSet<>(); //当前已选中的联系人昵称集合

    private static HashSet<String> exts=new HashSet<>();

    private Handler mHandler = null;

    private boolean isEnable=true;


    @Override
    public String getTargetPackageName() {

        return "com.tencent.mm";
    }

    @Override
    public void onCreateJob(AccessibilityService service) {
            this.service=service;
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    @Override
    public void onReceiveJob(AccessibilityEvent event) {
        AccessibilityNodeInfo rootNodeInfo=null;
        String className = event.getClassName().toString();
        switch (className){
            case "com.tencent.mm.ui.LauncherUI":
                    AccessibilityHelper.performClick(AccessibilityHelper.findNodeInfosByText(event.getSource(),"我"));
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                break;
            case "com.tencent.mm.plugin.setting.ui.setting.SettingsPluginsUI": //进入到微信功能界面并打开群发助手

                 openMessagePluginsUi();
                 break;
            case "com.tencent.mm.plugin.masssend.ui.MassSendSelectContactUI"://进入到群发选择联系人界面,开启记忆功能并自动选择
                 rootNodeInfo=service.getRootInActiveWindow();
                if(rootNodeInfo!=null){
                    listView=AccessibilityHelper.findNodeInfosById(rootNodeInfo,"com.tencent.mm:id/fc");
                }
                shareSelects=getManyShareCache();
                selectIndex=0;
                isNotMore=false;
                selectContact(200);
                break;

        }

    }

    private  void toSettingUI(){


    }

    @Override
    public void onStopJob() {
        isEnable=false;
    }

    @Override
    public void onNotificationPosted(IStatusBarNotification event) {

    }

    @Override
    public void setWeiXingVersion(int version) {

    }


    @Override
    public boolean isEnable() {
        return isEnable;
    }




    /**
     * 选择联系人
     * @param size
     */
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    private void  selectContact(int size){
        if(selectIndex==size || isNotMore){
            XToast.success("本轮已结束");
            return;
        }
        try {
            Thread.sleep(800);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        AccessibilityNodeInfo rootNodeInfo=service.getRootInActiveWindow();
        if(rootNodeInfo!=null){
             List<AccessibilityNodeInfo> nodeInfos=rootNodeInfo.findAccessibilityNodeInfosByViewId(CONTACT_ITEM_ID);
            for (AccessibilityNodeInfo n:nodeInfos ) {
                if(selectIndex==size){//已选择了指定数目的联系人就结束本
                    saveShareCache();
                    XToast.success("本轮已结束");
                    break;
                }
                if(n!=null){
                    AccessibilityNodeInfo nickNode=AccessibilityHelper.findNodeInfosByClassName(n,AccessibilityHelper.TEXT_VIEW_CLASS_NAME);
                    if(nickNode==null){ continue;} //过滤掉不正常的节点
                    String nickName=nickNode.getText().toString();
                    Log.i(TAG,nickName);
                    if(shareSelects.contains(nickName) || "选择一个群".equals(nickName)){//跳动已经选中的联系人（当然这里也同时会过滤掉重名的联系人）
                        continue;
                    }
                    if(AccessibilityHelper.performClick(n)){
                        shareSelects.add(nickName);
                        selectIndex+=1;
                    }
                    try {
                        Thread.sleep(300);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
            if(listView.performAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD)){
                listView.refresh();
                selectContact(size);
            }else {//如果已滑动到最底部
                isNotMore=true;
                selectContact(size);
            }
        }
    }

    /**
     * 获取已选中的人
     * @return
     */
    private HashSet<String>  getManyShareCache(){
        String  cachkey= XDateUtils.format(new Date(),"yyyyMMdd")+MANY_SHARE_CACHE_KEY;
        HashSet<String>  s= (HashSet<String>) XCache.get(getContext()).getAsObject(cachkey);
        if(s==null){
            s=new HashSet<>();
        }
        return s;
    }
    /**
     * 获取已选中的人
     * @return
     */
    private HashSet<String>  getShareCache(){
        String  cachkey= XDateUtils.format(new Date(),"yyyyMMdd")+SHARE_CACHE_KEY;
        HashSet<String>  s= (HashSet<String>) XCache.get(getContext()).getAsObject(cachkey);
        if(s==null){
            s=new HashSet<>();
        }
        return s;
    }
    /**
     * 获取已选中的人
     * @return
     */
    private void   saveShareCache(){
        String  cachkey= XDateUtils.format(new Date(),"yyyyMMdd")+SHARE_CACHE_KEY;
        XCache.get(getContext()).put(cachkey,shareSelects);
     }

    /**
     * 打开群发界面
     */
    private  void  openMessagePluginsUi(){
        AccessibilityNodeInfo rootNodeInfo=service.getRootInActiveWindow();
        if(rootNodeInfo!=null){
            AccessibilityNodeInfo nodes = AccessibilityHelper.findNodeInfosByText(rootNodeInfo,"群发助手");
            if(nodes!=null){
                AccessibilityHelper.performClick(nodes);
            }
        }
    }

    public ArrayList<HashMap<String, Object>> getItems(Context context) {

        PackageManager pckMan = context.getPackageManager();
        ArrayList<HashMap<String, Object>> items = new ArrayList<HashMap<String, Object>>();

        List<PackageInfo> packageInfo = pckMan.getInstalledPackages(0);

        for (PackageInfo pInfo : packageInfo) {

            HashMap<String, Object> item = new HashMap<String, Object>();

            item.put("appimage", pInfo.applicationInfo.loadIcon(pckMan));
            item.put("packageName", pInfo.packageName);
            item.put("versionCode", pInfo.versionCode);
            item.put("versionName", pInfo.versionName);
            item.put("appName", pInfo.applicationInfo.loadLabel(pckMan).toString());

            items.add(item);

        }

        return items;
    }

    private  Context  getContext(){
        return service.getApplicationContext();
    }
}
